
package com.skcc.cop.mrtaxi;


import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.MotionEvent;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.skcc.cop.mrtaxi.biz.destination.DestinationEntity;
import com.skcc.cop.mrtaxi.control.DataBaseControl;
import com.skcc.cop.mrtaxi.http.BizGateway;
import com.skcc.cop.mrtaxi.util.LocationUtils;
import com.skcc.cop.mrtaxi.util.LogControl;

/**
 * 
 * @author project team
 */ 
public class BaseActivity extends FragmentActivity {
    
	// ===========================================================
    // Constants
    // ===========================================================
    private static final String TAG = BaseActivity.class.getSimpleName();
    
    
    // ===========================================================
    // Fields
    // ===========================================================
    protected MrTaxiApplication application;  
    protected ProgressDialog progressDialog;
    protected BizGateway gateway;
    protected DataBaseControl dataBaseControl;
    
    
    // ===========================================================
    // Methods for/from SuperClass/Interfaces
    // ===========================================================
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
        LogControl.d(TAG, " in onCreate >>>>>");
        
        application = (MrTaxiApplication) this.getApplication();
        
        if (gateway == null) {
        	gateway = new BizGateway(this, MrTaxiApplication.SERVER_URL);
        }
        
        dataBaseControl = new DataBaseControl(BaseActivity.this);
    }

	@Override
    protected void onResume()
    {
        LogControl.d(TAG, " in onResume >>>>>");
        
        super.onResume();
    }
    
    @Override
    protected void onPause()
    {
        LogControl.d(TAG, " in onPause >>>>>");
        
        if (progressDialog != null && progressDialog.isShowing())
        {
            progressDialog.dismiss();
            progressDialog = null;
        }
        super.onPause();
    }
    
    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        
        LogControl.d(TAG, " in onDestroy >>>>>");
    }
    
    @Override
    public boolean dispatchTouchEvent(MotionEvent event)
    {
        return super.dispatchTouchEvent(event);
    }
    
    /*
     * Handle results returned to this Activity by other Activities started with
     * startActivityForResult(). In particular, the method onConnectionFailed() in
     * LocationUpdateRemover and LocationUpdateRequester may call startResolutionForResult() to
     * start an Activity that handles Google Play services problems. The result of this
     * call returns here, to onActivityResult.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

        // Choose what to do based on the request code
        switch (requestCode) {

            // If the request code matches the code sent in onConnectionFailed
            case LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST :

                switch (resultCode) {
                    // If Google Play services resolved the problem
                    case Activity.RESULT_OK:

                        // Log the result
                        LogControl.d(LocationUtils.APPTAG, getString(R.string.resolved));

                    break;

                    // If any other result was returned by Google Play services
                    default:
                        // Log the result
                        LogControl.d(LocationUtils.APPTAG, getString(R.string.no_resolution));

                    break;
                }

            // If any other request code was received
            default:
               // Report that this Activity received an unknown requestCode
               LogControl.d(LocationUtils.APPTAG, getString(R.string.unknown_activity_request_code, requestCode));

               break;
        }
    }
    
    
    // ===========================================================
    // Methods
    // ===========================================================
    /**
     * show a progress dialog if it is not showing.
     * 
     * @param resId
     */
    public void showProgressDialog(Context context, int loading)
    {
    	if (progressDialog == null || !progressDialog.isShowing())
        {
            try
            {
                progressDialog = ProgressDialog.show(context, getString(R.string.app_name), getString(loading), true);
                progressDialog.setContentView(R.layout.dialog_progress);
            } catch (Exception e)
            {
                // ignore this exception. maybe
                // android.view.WindowManager$BadTokenException will occurs when
                // activity is finishing.
            }
        }
    }
    
    /**
     * show a progress dialog if it is not showing.
     * 
     * @param resId
     */
    public void showProgressDialog(Context context)
    {
        if (progressDialog == null || !progressDialog.isShowing())
        {
            try
            {
                progressDialog = ProgressDialog.show(context, null, getString(R.string.loading), false, false);
            } catch (Exception e)
            {
                // ignore this exception. maybe
                // android.view.WindowManager$BadTokenException will occurs when
                // activity is finishing.
            }
        }
    }
    
    protected void setProgressDialogMessage(String message)
    {
        if (progressDialog != null && progressDialog.isShowing())
        {
            progressDialog.setMessage(message);
        }
    }
    
    /**
     * dismiss a progress dialog if it is showing.
     */
    public void dismissProgressDialog()
    {
        if (progressDialog != null && progressDialog.isShowing())
        {
            progressDialog.dismiss();
        }
    }
    
    protected boolean haveUserDestination() {
		ArrayList<DestinationEntity> destination = dataBaseControl.getDestinationListAll();
		LogControl.d(this, ""+destination.size());
		if (destination.size() == 0) {
			return false;
		}
		return true;
	}
    
    /**
     * Verify that Google Play services is available before making a request.
     *
     * @return true if Google Play services is available, otherwise false
     */
    protected boolean servicesConnected() {

        // Check that Google Play services is available
        int resultCode =
                GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

        // If Google Play services is available
        if (ConnectionResult.SUCCESS == resultCode) {
            // In debug mode, log the status
            LogControl.d(LocationUtils.APPTAG, getString(R.string.play_services_available));

            // Continue
            return true;
        // Google Play services was not available for some reason
        } else {
            // Display an error dialog
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(resultCode, this, 0);
            if (dialog != null) {
                ErrorDialogFragment errorFragment = new ErrorDialogFragment();
                errorFragment.setDialog(dialog);
                errorFragment.show(getSupportFragmentManager(), LocationUtils.APPTAG);
            }
            return false;
        }
    }
    
    /**
     * Show a dialog returned by Google Play services for the
     * connection error code
     *
     * @param errorCode An error code returned from onConnectionFailed
     */
    protected void showErrorDialog(int errorCode) {

        // Get the error dialog from Google Play services
        Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
            errorCode,
            this,
            LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST);

        // If Google Play services can provide an error dialog
        if (errorDialog != null) {

            // Create a new DialogFragment in which to show the error dialog
            ErrorDialogFragment errorFragment = new ErrorDialogFragment();

            // Set the dialog in the DialogFragment
            errorFragment.setDialog(errorDialog);

            // Show the error dialog in the DialogFragment
            errorFragment.show(getSupportFragmentManager(), LocationUtils.APPTAG);
        }
    }
    
    
	// ===========================================================
    // Inner and Anonymous Classes
    // ===========================================================
    /**
     * Define a DialogFragment to display the error dialog generated in
     * showErrorDialog.
     */
    public static class ErrorDialogFragment extends DialogFragment {

        // Global field to contain the error dialog
        private Dialog mDialog;

        /**
         * Default constructor. Sets the dialog field to null
         */
        public ErrorDialogFragment() {
            super();
            mDialog = null;
        }

        /**
         * Set the dialog to display
         *
         * @param dialog An error dialog
         */
        public void setDialog(Dialog dialog) {
            mDialog = dialog;
        }

        /*
         * This method must return a Dialog to the DialogFragment.
         */
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
        	mDialog.setCancelable(false);
            return mDialog;
        }
    }

}
